const express = require('express');
const router = express.Router();
const R = require("../util/json")
const connection = require("../util/db")
const json = require("../util/jsonFormat")
const md5 = require("md5")
const uuid = require("node-uuid")


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get("/test",function (req,res) {
  console.log(req.loginId);
  res.json(R.ok());
  // const sql = "select * from apply";
  // connection.query(sql,[],function (e,r,o) {
  //   if(e){
  //     throw e
  //   }
  //   res.json(R.data(json.formatArray(r,o)))
  // })
})

router.post('/login',function (req,res) {
  const {username,password} = req.body;
  let sql = "select * from userinfo where username = ? and password = ?";
  connection.query(sql,[username,md5(password)],function (e,r) {
    if(e){
      throw e;
    }
    if(r.length === 1){
      const user = r[0];
      if(user.status === 1){
        /*生成token*/
        const token = uuid.v4().replace(/-/g, '');
        /*设置有效期*/
        const date = new Date();
        date.setHours(date.getHours()+6);//6小时有效期
        /*token存入数据库*/
        sql = "select * from login where user_id = ?";
        connection.query(sql,user.id,function (e,r) {
          if(e){
            throw e;
          }
          if(r.length>0){//已存在用户登录信息，修改即可
            const login = r[0];
            sql="update login set token = ?,expires = ? where id = ?";
            connection.query(sql,[token,date,login.id],function (e,r) {
              if(e){
                throw e;
              }
              if(r.affectedRows > 0){
                res.json(R.data({token,expires:date.getTime()}));
              }else{
                res.json(R.error("token存储异常"))
              }
            })
          }else{
              sql = "insert into login values(null,?,?,?)";
              connection.query(sql,[user.id,token,date],function (e,r) {
                if(e){
                  throw e;
                }
                if(r.affectedRows > 0){
                  res.json(R.data({token,expires:date.getTime()}));
                }else{
                  res.json(R.error("token存储异常"))
                }
              })
          }
        })
      }else{
        res.json(R.error("该用户已被封禁！"))
      }
    }else if(r.length > 1){
      res.json(R.error("用户异常错误！"))
    }else{
      res.json(R.error("用户名或密码不正确！"));
    }
  })
})

router.post("/logout",function (req, res) {
  /*获取当前登录用户编号*/
  const userId = req.loginId;
  let sql = "update login set token = ? where user_id = ?";
  /*生成token*/
  const token = uuid.v4().replace(/-/g, '');
  connection.query(sql,[token,userId],function (e) {
    if(e){
      throw e;
    }
    res.json(R.ok());
  })
})

module.exports = router;
